package com.qianfeng.zhangwei.popupwindow;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.qianfeng.zhangwei.R;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class PopActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    PopupWindow popupWindow;
    TextView pop;

    private List<String> list = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pop);
        pop = (TextView) this.findViewById(R.id.pop);
        pop.setOnClickListener(this);
        initPopView();
    }

    private void initPopView() {
        for (int i = 0; i < 5; i++) {
            list.add("pop==============>>>" + i);
        }
        View popView = getLayoutInflater().inflate(R.layout.pop_layout, null);
        ListView listView = (ListView) popView.findViewById(R.id.pop_listView);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        popupWindow = new PopupWindow(popView);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.RED));
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        //触摸popwindwo 以外的区域popupwindow消失
        popupWindow.setOutsideTouchable(true);
//        popupWindow.showAsDropDown(pop);
    }

    @Override
    public void onClick(View v) {
        //显示popwindow
//        popupWindow.showAsDropDown(v);
//        popupWindow.showAsDropDown(v,50,110);
        popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            popupWindow.showAsDropDown(pop);
        }
    }
}
